﻿using System.Collections.Generic;
using System.Linq;
using Codeflows.Tracking;
using CodeflowsHost.Dashboard.Models;
using CodeflowsHost.Data;
using Nancy;
using CodeflowInstance = CodeflowsHost.Dashboard.Models.CodeflowInstance;

namespace CodeflowsHost.Dashboard.Modules
{
    public class DashboardModule : NancyModule
    {
		public DashboardModule()
        {
            Get["/"] = parameters => View["index"];

            Get["/overview"] = parameters =>
            {
                using(var db = new Database("Codeflows"))
                {
                	var totalCodeflows = db.ExecuteScalar<long>("SELECT COUNT(*) FROM CodeflowInstances");

                	var groupedStatuses = db.Query<GroupedCodeflowsStatusCount>(
                		"SELECT Status, COUNT(*) AS InstanceCount FROM CodeflowInstances GROUP BY Status")
                		.ToDictionary(x => x.Status, x => x.InstanceCount);
                    
					var recentCodeflows = db.Query<CodeflowInstance>("SELECT TOP 10 FriendlyName, Status, CreatedOnUtc, StartedAtUtc, LockedUntilUtc, ActionName FROM CodeflowInstances ORDER BY CreatedOnUtc DESC");

                    return Response.AsJson(new
                    {
						RecentCodeflows = recentCodeflows,
                    	TotalCodeflows = totalCodeflows, 
						NewCodeflows = GetCountForCodeflowStatus(groupedStatuses, CodeflowStatus.Created),
						RunningCodeflows = GetCountForCodeflowStatus(groupedStatuses, CodeflowStatus.Running),
						RunnableCodeflows = GetCountForCodeflowStatus(groupedStatuses, CodeflowStatus.Runnable),
						PausedCodeflows = GetCountForCodeflowStatus(groupedStatuses, CodeflowStatus.Paused),
                        SleepingCodeflows = GetCountForCodeflowStatus(groupedStatuses, CodeflowStatus.Sleeping),
						SuccessfulCodeflows = GetCountForCodeflowStatus(groupedStatuses, CodeflowStatus.Ended),
						FailedCodeflows = GetCountForCodeflowStatus(groupedStatuses, CodeflowStatus.Terminated, CodeflowStatus.Suspended)
                    });
                }
            };
        }

		private static long GetCountForCodeflowStatus(IDictionary<CodeflowStatus, long> groupedStatuses, params CodeflowStatus[] statusList)
		{
			return statusList.Sum(status => groupedStatuses.ContainsKey(status) ? groupedStatuses[status] : 0);
		}
    }
}